package org.zk.dubbo_consumer.controller;


import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.zk.entity.*;
import org.zk.service.BroadcastService;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import org.zk.dubbo_consumer.utils.AddLiveStreamTranscodeUtil;
import org.zk.dubbo_consumer.utils.AliPlayAndPushUtil;
import org.zk.dubbo_consumer.utils.PinYinUtil;
import org.zk.entity.Broadcast;
import org.zk.entity.Teacher;
import org.zk.service.LessionBroadcastService;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Alicelonely
 * @since 2019-12-11
 */
@Controller
@RequestMapping("/broadcast")
public class BroadcastController {

    @Resource
    private BroadcastService broadcastService;

    @Resource
    private LessionBroadcastService lessionBroadcastService;


    /**
     * @MethodName: getLiveServer
     * @Description: 给老师分配个人直播服务器地址
     * @Param: []
     * @Return: java.lang.String
     * @Author: 刘艺广
     * @Time: 2019/12/19 0019 上午 10:28
     **/
    @ResponseBody
    @RequestMapping("/getLiveServer")
    public String getLiveServer(HttpSession session) {

        Teacher teacher= (Teacher) session.getAttribute("teacher");
        String teacherName=teacher.getTeacherName();
        int teacherId=teacher.getTeacherId();
        String appName=PinYinUtil.ToPinyin(teacherName)+String.valueOf(teacherId);
        /**
         * 此处应在session中取得老师的个人资料，但现在用真实数据模拟
         * 用老师的 "名字全名+id" 作为appName,用房间号作为streamName
         */

        //获得主播的个人直播服务器地址
        String serverUrl = AliPlayAndPushUtil.CreateServer(appName);
        //为主播配置转码模板
        AddLiveStreamTranscodeUtil.addTranscode(appName);

        return serverUrl;
    }

    /**
     * @MethodName: getSecretKey
     * @Description: 获得直播的串流密钥
     * @Param: []
     * @Return: java.lang.String
     * @Author: 刘艺广
     * @Time: 2019/12/19 0019 上午 10:30
     **/
    @ResponseBody
    @RequestMapping("/getSecretKey")
    public String getSecretKey(HttpSession session) {

        Teacher teacher= (Teacher) session.getAttribute("teacher");
        String teacherName=teacher.getTeacherName();
        int teacherId=teacher.getTeacherId();
        String appName=PinYinUtil.ToPinyin(teacherName)+String.valueOf(teacherId);

        /**
         * 此处应在session中取得老师的个人资料，但现在用真实数据模拟
         * 用老师的 "名字全名+id" 作为appName,用房间号作为streamName
         */

        String streamName = teacher.getTeacherRoom();
        //获得直播的串流密钥
        String secretKey = AliPlayAndPushUtil.CreateSecretKey(appName, streamName);
        return secretKey;
    }


    /**
     * @MethodName: toWatchLive
     * @Description: 根据直播Id获得拉流地址, 并进入直播间观看直播
     * @Param: [broadcastId]
     * @Return: java.lang.String
     * @Author: 刘艺广
     * @Time: 2019/12/19 0019 上午 10:55
     **/
    @RequestMapping("/toWatchLive/{id}")
    public ModelAndView toWatchLive(@PathVariable("id") int broadcastId,HttpSession session) {
        System.out.println(broadcastId);
        Broadcast broadcast = broadcastService.getBroadcastAndTeacherByBroadcastId(broadcastId);
        String appName = PinYinUtil.ToPinyin(broadcast.getTeacher().getTeacherName()) + broadcast.getTeacher().getTeacherId().toString();
        String streamName = broadcast.getTeacher().getTeacherRoom();
        //为前台地址栏设置标题
        String title = broadcast.getTeacher().getTeacherName() + "-----" + broadcast.getBroadcastTitle();
        Map pullUrlMap = new HashMap();
        pullUrlMap = AliPlayAndPushUtil.GetPlayUrl(appName, streamName);
//        ServletContext context =  session.getServletContext();
         User user= (User) session.getAttribute("user");

        ModelAndView mv = new ModelAndView("user/live");
        mv.addObject("pullUrlMap", pullUrlMap);
        mv.addObject("title", title);
        mv.addObject("user",user);
        mv.addObject("id",broadcastId);
        System.out.println("================================================");
        System.out.println(user.getUserName());
        return mv;
    }

    /**
     * 添加直播信息，数据和封面，上传服务器需要更改保存的路径
     * @param file
     * @param teacherId
     * @param broadcastBegtime
     * @param broadcastEndtime
     * @param broadcastIntroduction
     * @param broadcastPrice
     * @param broadcastState
     * @param typeId
     * @param subjectId
     * @param broadcastTitle
     * @return
     */
    @ResponseBody
    @RequestMapping("/addBroadcast")
    public ModelAndView addaddBroadcast(@RequestParam("file") MultipartFile file,@RequestParam("teacherId") int teacherId,@RequestParam("broadcastBegtime") String broadcastBegtime,@RequestParam("broadcastEndtime") String broadcastEndtime,@RequestParam("broadcastIntroduction") String broadcastIntroduction,@RequestParam("broadcastPrice") Double broadcastPrice,@RequestParam("broadcastState") int broadcastState,@RequestParam("typeId") int typeId,@RequestParam("subjectId") int subjectId,@RequestParam("broadcastTitle") String broadcastTitle) {
        Teacher teacher = new Teacher();
        teacher.setTeacherId(teacherId);
        Type type = new Type();
        type.setTypeId(typeId);
        Subject subject = new Subject();
        subject.setSubjectId(subjectId);
        Broadcast broadcast = new Broadcast();
        broadcast.setBroadcastIntroduction(broadcastIntroduction);
        broadcast.setBroadcastBegtime(broadcastBegtime);
        broadcast.setBroadcastEndtime(broadcastEndtime);
        broadcast.setBroadcastTitle(broadcastTitle);
        broadcast.setBroadcastPrice(broadcastPrice);
        broadcast.setBroadcastState(broadcastState);
        String fileName = file.getOriginalFilename();  // 文件名
        if (!"".equals(fileName)) {
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            File fileMkdir = new File("D:\\dubbo_pumpkin\\dubbo_consumer\\src\\main\\resources\\static\\picture");
            if (!fileMkdir.exists()) {
                fileMkdir.mkdir();
            }
            String filePath = fileMkdir.getPath() + "\\";
            fileName = UUID.randomUUID() + suffixName;  //新文件名
            File dest = new File(filePath + fileName);
            try {
                //写入文件
                file.transferTo(dest);
            } catch (IOException e) {
            }
        }
        Map map = new HashMap();
        broadcast.setBroadcastCover(fileName);
        broadcast.setTeacher(teacher);
        broadcast.setType(type);
        broadcast.setSubject(subject);
        int result = broadcastService.insertBroadcast(broadcast);
        if (result > 0) {
            return new ModelAndView("teacher/lession_add");
        } else {
            return new ModelAndView("/teacher/course-add");
        }
    }

    /**
     * 更改直播信息，预留的控制器
     * @param broadcast
     * @param teacher
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateBroadcast")
    public Map updateBroadcast(Broadcast broadcast, Teacher teacher) {
        Map map = new HashMap();
        broadcast.setTeacher(teacher);
        if ("".equals(broadcast.getBroadcastIntroduction())) {
            broadcast.setBroadcastIntroduction(null);
        }
        if (" ".equals(broadcast.getBroadcastBegtime())) {
            broadcast.setBroadcastBegtime(null);
        }
        if (" ".equals(broadcast.getBroadcastEndtime())) {
            broadcast.setBroadcastEndtime(null);
        }
        if ("".equals(broadcast.getBroadcastTitle())) {
            broadcast.setBroadcastTitle(null);
        }
        int result = broadcastService.updateBroadcast(broadcast);
        if (result > 0) {
            map.put("right", "right");
        } else {
            map.put("error", "error");
        }
        return map;
    }

    /**
     * 分页查询所有直播的信息
     * @param broadcast
     * @param teacher
     * @param choise
     * @param pageSize
     * @param pageNum
     * @return
     */
    @ResponseBody
    @RequestMapping("/getBroadcastByIdByPage")
    public Map getBroadcastByIdByPage(Broadcast broadcast, Teacher teacher, int choise, int pageSize, int pageNum) {
        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", pageSize);
        map.put("pageNum", pageNum);
        String currTime = null;
        //choise=1 是正在直播 2是未开始直播 3是一结束直播 choise=0是查所有的直播
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        currTime = df.format(new Date());
        broadcast.setTeacher(teacher);
        map.put("currTime", currTime);
        map.put("broadcast", broadcast);
        map.put("choise", choise);

        PageInfo page = broadcastService.getBroadcastByIdByPage(map);
        List<Broadcast> ls = page.getList();
        for (int i = 0; i < ls.size(); i++) {
            String name = ls.get(i).getBroadcastCover();
            ls.get(i).setBroadcastCover("/static/image/picture/" + name);
            String flag = ls.get(i).getBroadcastFlag();
            if (flag.equals("0")) {
                ls.get(i).setBroadcastFlag("待审核");
            }
            if (flag.equals("1")) {
                ls.get(i).setBroadcastFlag("已通过");
            }
            if (flag.equals("2")) {
                ls.get(i).setBroadcastFlag("拒绝");
            }
        }
        map.put("page", page);
        map.put("totalPage", page.getPages());
        return map;
    }

    /**
     * 根据id删除该项直播
     * @param broadcast
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteBroadcastById")
    public Map deleteBroadcastById(Broadcast broadcast) {
        Map map = new HashMap();
        int result = broadcastService.deleteBroadcastById(broadcast);
        if (result > 0) {
            map.put("success", "success");
            return map;
        } else {
            map.put("error", "error");
            return map;
        }
    }

    /**
     * 分页查询所有的直播
     * @param pageSize
     * @param pageNum
     * @param state
     * @return
     */
    @ResponseBody
    @RequestMapping("/getBoradcastList")
    public Map getBoradcastList(int pageSize, int pageNum, String state) {
        Map<String, Object> map = new HashMap<>();
        Broadcast broadcast = new Broadcast();
        broadcast.setBroadcastFlag(state);
        map.put("broadcast", broadcast);
        map.put("pageSize", pageSize);
        map.put("pageNum", pageNum);
        PageInfo page = broadcastService.getAllBroadcastPage(map);
        List<Broadcast> ls = page.getList();
        for (int i = 0; i < ls.size(); i++) {
            String name = ls.get(i).getBroadcastCover();
            ls.get(i).setBroadcastCover("/static/image/picture/" + name);
            String flag = ls.get(i).getBroadcastFlag();
            if (flag.equals("0")) {
                ls.get(i).setBroadcastFlag("待审核");
            }
            if (flag.equals("1")) {
                ls.get(i).setBroadcastFlag("已通过");
            }
            if (flag.equals("2")) {
                ls.get(i).setBroadcastFlag("拒绝");
            }
        }
        map.put("page", page);
        map.put("totalPage", page.getPages());
        return map;
    }

    /**
     * 审核broadcast(同意)
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/broadcastAgree")
    public List broadcastAgree(Broadcast broadcast) {
        List ls = new ArrayList();
        broadcast.setBroadcastFlag("1");
        int result = broadcastService.updateFlag(broadcast);
        if (result > 0) {
            ls.add("succ");
            return ls;
        }
        return ls;
    }

    /**
     * 审核broadcast（拒绝）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/broadcastRefuse")
    public List refusebroadcast(Broadcast broadcast) {
        List ls = new ArrayList();
        broadcast.setBroadcastFlag("2");
        int result = broadcastService.updateFlag(broadcast);
        if (result > 0) {
            ls.add("succ");
            return ls;
        }
        return ls;
    }

    /**
     * 查看直播详情页
     *
     * @param broadcastId
     * @return
     */
    @RequestMapping("/toList")
    public ModelAndView toList(int broadcastId) {
        ModelAndView modelAndView = new ModelAndView("teacher/teacherconter/list");
        modelAndView.addObject("broadcastId", broadcastId);
        return modelAndView;
    }

    /**
     * 获取直播的目录
     * @param broadcastId
     * @return
     */
    @ResponseBody
    @RequestMapping("/getBroadcastLessionById")
    public List<LessionBroadcast> getBroadcastLessionById(int broadcastId) {
        return lessionBroadcastService.getBroadcastLessionById(broadcastId);
    }

    /**
     * 删除当前直播的目录
     * @param lessionBroadcast
     * @return
     */
    @ResponseBody
    @RequestMapping("/delBroadcastLessionById")
    public List delBroadcastLessionById(LessionBroadcast lessionBroadcast) {
        List ls = new ArrayList();
        int result = lessionBroadcastService.delBroadcastLessionById(lessionBroadcast);
        if (result > 0) {
            ls.add("succ");
            return ls;
        }
        return ls;
    }

    /**
     * 进入teacher的每一节直播
     * @param broadcast
     * @param lessionBroadcast
     * @return
     */
    @ResponseBody
    @RequestMapping("/teacherBroadcastEveryAdd")
    public List teacherBroadcastEveryAdd(Broadcast broadcast, LessionBroadcast lessionBroadcast) {
        lessionBroadcast.setBroadcast(broadcast);
        int result = lessionBroadcastService.addLessionBroadcast(lessionBroadcast);
        List<LessionBroadcast> ls = null;
        if (result > 0) {
            ls = new ArrayList<>();
        }
        ls.add(lessionBroadcast);
        return ls;
    }

    //上传课程视频
    @ResponseBody
    @RequestMapping("/teacherBroadcastEveryFileAdd")
    public List addLession(@RequestParam("files") MultipartFile[] files, @RequestParam("lessionBroadcastId") int lessionBroadcastId) {
        List list = new ArrayList();
        String videoName = "";
        String newVideoName = "";
        String lessionBroadcastVideoName = "";
        String lessionBroadcastVideo = "";
        for (MultipartFile file : files) {
            videoName = file.getOriginalFilename();
            if ("".equals(videoName)) continue;
            String suffix = videoName.substring(videoName.lastIndexOf("."));
            File fileMkdir = new File("E:\\courseVideo");
            if (!fileMkdir.exists()) {
                fileMkdir.mkdir();
            }
            String filePath = fileMkdir.getPath() + "\\";
            newVideoName = UUID.randomUUID() + suffix;  //作为lession表的video存入
            lessionBroadcastVideo += newVideoName  ;
            lessionBroadcastVideoName += videoName ;

            File dest = new File(filePath + newVideoName);
            try {
                //写入文件
                file.transferTo(dest);
            } catch (IOException e) {
                return list;
            }
        }

        LessionBroadcast lessionBroadcast = new LessionBroadcast();
        lessionBroadcast.setLessionBroadcastVideo(lessionBroadcastVideo);
        lessionBroadcast.setLessionBroadcastId(lessionBroadcastId);
        lessionBroadcast.setlessionBroadcastVideoName(lessionBroadcastVideoName);
        int result = lessionBroadcastService.updateLessionBroadcast(lessionBroadcast);

        if (result > 0) {
            list.add("succ");
        } else {
            list.add("error");
        }
        return list;
    }

    /**
     * 直播详情页
     *
     * @param broadcastId
     * @return
     */
    @RequestMapping("/toBroadcastMsg")
    public ModelAndView toCourse(int broadcastId, HttpSession session) {

      /*  //gs修改，==============================
        //模拟用户登录，存放session
        User user = new User();
        user.setUserId(2);
        user.setUserName("好好学习");
        user.setUserVip(1);//会员
        session.setAttribute("user", user);
        //======================================*/

        Broadcast broadcast= broadcastService.getBroadcastById(broadcastId);
        List<LessionBroadcast> lessionBroadcastList = lessionBroadcastService.getBroadcastLessionById(broadcast.getBroadcastId());
        Map map = new HashMap();
        map.put("broadcast", broadcast);
        int broadcastCount = broadcastService.getBroadcastCountByIdByPageint(map);//该教师发布的直播数量
        PageInfo broadcastListPage = broadcastService.getBroadcastByIdByPage(map);//该教师发布的所有课程
        List<Broadcast> broadcastList= broadcastListPage.getList();

        String name = broadcast.getBroadcastCover();
        String path = "/static/picture/" + name;
        ModelAndView modelAndView = new ModelAndView("user/broadcastMsg");
        modelAndView.addObject("lessionBroadcastList", lessionBroadcastList);  //目录
        modelAndView.addObject("broadcast", broadcast);
        modelAndView.addObject("path", path);
        modelAndView.addObject("broadcastCount", broadcastCount);
        modelAndView.addObject("broadcastList", broadcastList);
        return modelAndView;

    }


    @RequestMapping("/toOrg")
    public String toOrg() {
        return "teacher/teacherconter/org-detail-course";
    }

    @RequestMapping("/toTeacherManage")
    public String toTeacherManage() {
        return "teacher/teacherconter/teachermanage";
    }

    @RequestMapping("/toTeacherAllList")
    public String toTeacherAllList() {
        return "teacher/teacherconter/teacher-broadcast-alllist";
    }

    @RequestMapping("/toTeacherBroadcastAdd")
    public ModelAndView toTeacherBroadcastAdd(Broadcast broadcast) {
        ModelAndView modelAndView = new ModelAndView("teacher/teacherconter/teacher-broadcast-add");
        modelAndView.addObject("broadcast", broadcast);
        return modelAndView;
    }



    @RequestMapping("/toTeacherBeingList")
    public String toTeacherBeingList() {
        return "teacher/teacherconter/teacher-broadcast-beinglist";
    }

    @RequestMapping("/toTeacherAlreadyList")
    public String toTeacherAlreadyList() {
        return "teacher/teacherconter/teacher-broadcast-alreadylist";
    }

    @RequestMapping("/toTeacherNotList")
    public String toTeacherNotList() {
        return "teacher/teacherconter/teacher-broadcast-notlist";
    }


    @RequestMapping("/toTeacherBroadcastEveryFileAdd")
    public ModelAndView toTeacherBroadcastEveryFileAdd(int lessionBroadcastId) {
        ModelAndView modelAndView = new ModelAndView("teacher/teacherconter/teacher-broadcast-every-file-add");
        modelAndView.addObject("lessionBroadcastId", lessionBroadcastId);
        return modelAndView;
    }

    @RequestMapping("/toTeacherBroadcastEveryAdd")
    public ModelAndView toTeacherBroadcastEveryAdd(int broadcastId) {
        ModelAndView modelAndView = new ModelAndView("teacher/teacherconter/teacher-broadcast-every-add");
        modelAndView.addObject("broadcastId", broadcastId);
        return modelAndView;
    }


}

